#include "mostusedquantizer.h"
#include <algorithm>

namespace WingGif {

MostUsedQuantizer::MostUsedQuantizer() : PaletteQuantizer(QVector<QColor>()) {}

void MostUsedQuantizer::firstPass(QByteArray pixels) {
  // Pixels are in BGRA.
  colors.clear();

  for (auto index = 0; index < pixels.length(); index += 4) {
    // Transparent colors are ignored.
    if (!pixels[index + 3])
      continue;
    colors.append(
        QColor::fromRgb(pixels[index + 2], pixels[index + 1], pixels[index]));
  }
}

QVector<QColor> MostUsedQuantizer::buildPalette() {
  auto _transparentColor = transparentColor();
  auto _maxColors = maxColors();
  auto _maxColorsWithTransparency =
      _transparentColor.isValid() ? _maxColors - 1 : _maxColors;

  setMaxColorsWithTransparency(_maxColorsWithTransparency);

  auto c = colors;
  std::sort(c.begin(), c.end(), [=](QColor &first, QColor &second) {
    return first.rgba() < second.rgba();
  });
  auto it = std::unique(c.begin(), c.end());
  c.erase(it, c.end());

  struct ColorInfo {
    QColor color;
    int count;
  };

  QVector<ColorInfo> record(c.count());
  for (auto i = 0; i < c.count(); i++) {
    record[i] = ColorInfo{c[i], colors.count(c[i])};
  }
  std::sort(record.begin(), record.end(),
            [](ColorInfo &first, ColorInfo &second) {
              return first.count > second.count;
            });

  QVector<QColor> colorTable(_maxColorsWithTransparency);
  for (auto i = 0; i < _maxColorsWithTransparency; i++) {
    colorTable[i] = record[i].color;
  }

  return colorTable;
}

} // namespace WingGif
